package com.ojoin.trade.common_core.web.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.EmailSendUtil;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.SMSHelper;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.utils.paynow.IAccountConst;
import com.ojoin.trade.common.web.controller.BaseController;
import com.ojoin.trade.common.web.controller.BaseControllerImpl;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.domain.SessionUser;
import com.ojoin.trade.common.web.service.IRSAService;
import com.ojoin.trade.common_core.utils.TradeUtils;
import com.ojoin.trade.common_core.web.domain.MerchantUserInfo;
import com.ojoin.trade.common_core.web.domain.RealNameUserVO;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbMerchantUser;
import com.ojoin.trade.common_core.web.domain.TbMerchantUserBusinessType;
import com.ojoin.trade.common_core.web.domain.TbMerchantuserFinaccount;
import com.ojoin.trade.common_core.web.service.BranchBaseService;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantuserFinaccountService;

@Controller
@RequestMapping("/merchantuser")
public class MerchantUserController extends BaseControllerImpl<TbMerchantUser> implements BaseController<TbMerchantUser>{
	private Logger log = LoggerFactory.getLogger(MerchantUserController.class);

	@Autowired
	private MerchantUserBaseService userService;
	
	@Autowired
    private BranchBaseService branchBaseService;
	
	@Autowired
    private TbMerchantInfoBaseService tbMerchantInfoBaseService;
	
	@Autowired
	private IRSAService rsaSrv;

    @Autowired
    private TbMerchantuserFinaccountService tbMerchantuserFinaccountService;

	@Override
	protected MerchantUserBaseService getBaseService() {
		return userService;
	}

	 
	@ResponseBody
	@RequestMapping(value = "/preRealName", method = RequestMethod.POST)
	public Result preRealName(HttpServletRequest request) {
		String mhtNo = TradeUtils.getMhtNo(request);
		try {
			List list = getBaseService().preRealNameByPayUser(mhtNo);
			Map<String, String> data = (Map) list.get(1);
			if (CommonUtils.isSuccess(list)) {
				return new Result(Status.OK, data);
			} else {
				return CommonUtils.buildError(list);
			}
		} catch (Exception e) {
			log.error("预实名失败", e);
			return new Result(Status.ERROR, "预实名失败");
		}

	}
	
	@ResponseBody
	@RequestMapping(value = "/RealName", method = RequestMethod.POST)
	public Result RealName(HttpServletRequest request,
			@RequestParam String mchType, 
			RealNameUserVO realName,
			String mobileVerifyCode,
			String mobileVerifyCodeP) {
		
		SessionUser user=CommonUtils.getSessionUser(request);
		String mhtNo=user.getMhtNo();
		String mhtType=user.getMchType();
		//TODO:mobile dup check
		
		//实名提交后，不在验证
		if("0".equals(user.getRealStatus())){
			String verifyCode=IConstDef.Type_INDIVIDUAL.equals(mhtType)?mobileVerifyCodeP:mobileVerifyCode;
			boolean isValidShortMsgCode=SMSHelper.validateMobileCode(mhtNo, verifyCode);
			
			if (!isValidShortMsgCode) {
				return new Result(Status.ERROR, "验证码错误");
			}
		}
		
		//yyyyMMdd
		String certDate=realName.getCertDate();
		if(StringUtils.isNotEmpty(certDate)){
			certDate=certDate.replaceAll("-", "");
			realName.setCertDate(certDate);
		}
		
		//三证处理
		if("3".equals(realName.getDoctype())){
			realName.setTaxNo(realName.getLicNo());
			realName.setOrgNo(realName.getLicNo());
		}
		
		try {
			List list=null;
			if(IAccountConst.AUTICATION_MCHTYPE_ENTERPRISE.equals(mchType)){
				list = getBaseService().realNameEnterpriseByPayUserInfo(
						mhtNo, realName.getMchName(), realName.getMobile(), 
						realName.getName(), realName.getCertNo(), realName.getLicNo(), realName.getTaxNo(), realName.getCertDate(),
						realName.getOpenNo(), realName.getOrgNo(), 
						realName.getCardMobile(), realName.getCardNo(), realName.getCardProvince(), realName.getCardCity(),realName.getBranchNo());
			}else{
				list = getBaseService().realNameIndividualByPayUserInfo(
						mhtNo,realName.getMchName(), realName.getMobile(), realName.getName(), 
						realName.getCertNo(), realName.getCertDate(), 
						realName.getCardMobile(), realName.getCardNo(), realName.getCardProvince(), realName.getCardCity(),realName.getBranchNo());
			}
			
			if (CommonUtils.isSuccess(list)) {
				//九盈本地缓存实名信息
				TbMerchantInfo info=buildMerchantInfo(user, realName);
				info.formateDate();
				info.setRealStatus("1");
				tbMerchantInfoBaseService.addTbMerchantInfo(info);
				
				Map<String, String> data = (Map) list.get(1);
				//移除验证码cache
				SMSHelper.clearMobileValidateCode(mhtNo);
				return new Result(Status.OK, "/user/userAccount", data);
			} else {
				return CommonUtils.buildError(list);
			}
		} catch (Exception e) {
			log.error("登陆用户ID {} ,实名失败", new String[]{mhtNo},e);
			return new Result(Status.ERROR, "实名失败");
		}
	}
	
	
	private TbMerchantInfo buildMerchantInfo(SessionUser user, RealNameUserVO realName) {
		TbMerchantInfo minfo=new TbMerchantInfo();
		try {
			BeanUtils.copyProperties(minfo, realName);
			minfo.setIdOfTbMerchantUser(user.getId());
			minfo.setMhtNo(user.getMhtNo());
		} catch (Exception e) {
			LogUtils.error(log, "实名VO转换本地VO异常");
			throw new BusinessException(e.getMessage());
		}
		return minfo;
	}


	@ResponseBody
	@RequestMapping(value = "/sendVirtualBankAccount", method = RequestMethod.GET)
	public Result sendVirtualBankAccount (HttpServletRequest request) {
		String mhtNo = TradeUtils.getMhtNo(request);
		String mail=CommonUtils.getSessionUser(request).getLoginName();
		try {
			
			SessionUser payUser=CommonUtils.getSessionUser(request);
			
			List<TbMerchantuserFinaccount> list = tbMerchantuserFinaccountService.queryFinaccountByJoinidAndAcctype(payUser.getId(),IConstDef.CMBC_TYPE);
			if (!CommonUtils.isEmpty(list)) {
                TbMerchantuserFinaccount vo = list.get(0);
				// 发送内容
				String msgcontent = "【九盈】您的结算账户为：" +vo.getFinanceAccount();
				String sub="【九盈】您的结算账户信息";
				log.info("正在发送邮件 收件人:{} 内容:{}",new String[]{mail,msgcontent});
				
				boolean isSuccess=EmailSendUtil.send(mail,sub, msgcontent);
				
				return new Result(isSuccess,"您的账户信息已发送");
			} else {
				return CommonUtils.buildError(list);
			}
		} catch (Exception e) {
			log.error("登陆用户ID  {} ,发送虚拟账户失败", new String[]{mhtNo},e);
			return new Result(Status.ERROR, "发送虚拟账户失败");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/queryMerchantUser", method = RequestMethod.GET)
	public Result queryMerchantUser(HttpServletRequest request) {
		String mhtNo = TradeUtils.getMhtNo(request);
		try {
			SessionUser payUser=CommonUtils.getSessionUser(request);
			
			List list = getBaseService().queryPayUserVOByID(mhtNo);
			if (CommonUtils.isSuccess(list)) {
				Map<String, String> data = (Map) list.get(1);
				String result = data.get("mhtData");
				MerchantUserInfo muser = JSONUtils.parseObject(result,MerchantUserInfo.class);
				
				if(null!=muser){
					muser.formateDate();
					muser.setLoginNo(payUser.getLoginName());
					if(null!=muser.getBranchNo()){
			        	String displayBranchNo=branchBaseService.queryDisplayBranchNo(muser.getBranchNo());
			        	muser.setDisplayBranchNo(displayBranchNo);
					}
                    List<TbMerchantuserFinaccount> accountlist=tbMerchantuserFinaccountService.queryFinaccountByJoinidAndAcctype(payUser.getId(),IConstDef.CMBC_TYPE);
                    if(!CommonUtils.isEmpty(accountlist)){
                        muser.setBankAccount(accountlist.get(0).getFinanceAccount());
                    }else{
                        muser.setBankAccount("暂未开户");
                    }
		        }

				
				return new Result(Status.OK, muser);
			} else {
				return CommonUtils.buildError(list);
			}
		} catch (Exception e) {
			log.error("登陆用户ID  {} ,查询商户信息失败", new String[]{mhtNo},e);
			return new Result(Status.ERROR, "查询商户信息失败");
		}
	}



    @ResponseBody
    @RequestMapping(value="/queryMchName",method = RequestMethod.POST)
    private Result queryMchName(HttpServletRequest request){

     try{
         String mchName=TradeUtils.getMchName(request);
         return new Result(Status.OK,mchName);
     }catch (Exception e){
         return new Result(Status.ERROR,"查询失败");
     }
    }

	@ResponseBody
	@RequestMapping(value = "/queryUser", method = RequestMethod.GET)
	public Result queryUser(HttpServletRequest request) {
		String mhtNo = TradeUtils.getMhtNo(request);
		try {
			TbMerchantUser user = getBaseService().queryJoinUser(mhtNo);
			return new Result(Status.OK, user);
		} catch (Exception e) {
			return new Result(Status.ERROR, "查询用户失败");
		}
	}

	@ResponseBody
	@RequestMapping(value = "/setPayPwd", method = RequestMethod.POST)
	public Result setPayPwd(HttpServletRequest request,
			@RequestParam String newPasswd) {
		String mhtNo = TradeUtils.getMhtNo(request);
		if (StringUtils.isEmpty(newPasswd)) {
			return new Result(Status.ERROR, "请输入支付密码");
		}
		try {
			newPasswd = rsaSrv.decryptStringByJs(newPasswd);
			List list = getBaseService().setPayPwd(mhtNo, newPasswd);
			Map<String, String> data = (Map) list.get(1);
			if (CommonUtils.isSuccess(list)) {
				SMSHelper.clearModifyAccountInfoValidateCode(mhtNo);
				return new Result(Status.OK, data);
			} else {
				return CommonUtils.buildError(list);
			}
		} catch (Exception e) {
			log.error("设置支付密码失败", e);
			return new Result(Status.ERROR, "设置支付密码失败");
		}
	}

	@ResponseBody
	@RequestMapping(value = "/updatePayPwd", method = RequestMethod.POST)
	public Result updatePayPwd(HttpServletRequest request, String oldPasswd,
			String newPasswd) {
		String mhtNo = TradeUtils.getMhtNo(request);
		if (StringUtils.isEmpty(oldPasswd)) {
			return new Result(Status.ERROR, "请输入原密码");
		}
		if (StringUtils.isEmpty(newPasswd)) {
			return new Result(Status.ERROR, "请输入新密码");
		}
		try {
			oldPasswd = rsaSrv.decryptStringByJs(oldPasswd);
			newPasswd = rsaSrv.decryptStringByJs(newPasswd);
			List list = getBaseService().updatePayPwd(mhtNo, oldPasswd,
					newPasswd);
			Map<String, String> data = (Map) list.get(1);
			if (CommonUtils.isSuccess(list)) {
				SMSHelper.clearModifyAccountInfoValidateCode(mhtNo);
				return new Result(Status.OK, data);
			} else {
				return CommonUtils.buildError(list);
			}
		} catch (Exception e) {
			log.error("更新支付密码失败", e);
			return new Result(Status.ERROR, "更新支付密码失败");
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "/updateLoginPwd", method = RequestMethod.POST)
	public Result updateLoginPwd(HttpServletRequest request,
			@RequestParam String oldPasswd, @RequestParam String newPasswd) {
		String mhtNo = TradeUtils.getMhtNo(request);
		if (StringUtils.isEmpty(oldPasswd)) {
			return new Result(Status.ERROR, "请输入原密码");
		}
		if (StringUtils.isEmpty(newPasswd)) {
			return new Result(Status.ERROR, "请输入新密码");
		}
		try {
			List list = getBaseService().updateLoginPwd(mhtNo, oldPasswd,
					newPasswd);
			Map<String, String> data = (Map) list.get(1);
			if (CommonUtils.isSuccess(list)) {
				return new Result(Status.OK, data);
			} else {
				return CommonUtils.buildError(list);
			}
		} catch (Exception e) {
			log.error("更新登录密码失败", e);
			return new Result(Status.ERROR, "更新登录密码失败");
		}
	}
	
	
    /**
     * 查询商户的已开通贷款类型及负债额
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/querymerchanttype",method = RequestMethod.GET)
    public Result queryMerchantType(HttpServletRequest request){
    	int joinuserid=CommonUtils.getSessionUser(request).getId();
        try{
        TbMerchantUserBusinessType type=getBaseService().queryBusinessTypeByJoinuserId(joinuserid);
        return new Result(Status.OK,type);
        }catch (Exception e){
            log.error("查询商户->" + joinuserid +"已开通贷款类型及负债额出错",e);
            if(e instanceof BusinessException){
                return new Result(Status.ERROR,e.getMessage());
            }
            return new Result(Status.ERROR,"查询商户->" + joinuserid +"已开通贷款类型及负债额出错");
        }

    }
}